# -*- coding: utf8 -*-


import zlib
from project.mysql.table import Table
from pymysql import Binary

class TableImageVectorBig( Table ):

    _table_name = "image_vector_big"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS %s (" % self._table_name+
            "image_id INTEGER UNSIGNED PRIMARY KEY, "+
            "file_id INTEGER UNSIGNED NOT NULL, "+
            "orientation TINYINT(1) UNSIGNED NOT NULL, "+
            "mode CHAR(1) NOT NULL, "+
            "vector BLOB NOT NULL) ENGINE %s" % self.getEngine()
        )
        try:
            cur.execute(
                "ALTER TABLE `%s` ADD INDEX files (file_id)" % self._table_name
            )
        except:
            pass
        cur.close()
        return


    def insert( self, file_id, image_id, orientation, vector ):

        # print(self.__class__.__name__ + " :: insert vector: %r" % (vector,))

        v_str = (''.join([ chr(v) for v in vector ])).encode('utf8')

        len_array = len(v_str)

        gz_str = zlib.compress(v_str, 9)

        code = 's'
        if len_array > len(gz_str):
            code = 'g'
            v_str = gz_str

        v_str = Binary(v_str)
        cur = self.getCursor()
        v_id = cur.execute(
            "INSERT INTO %s(" % self._table_name+
            "file_id, image_id, orientation, mode, vector"
            ") VALUES (%s, %s, %s, %s, %s)", (
                file_id, image_id, orientation, code, v_str
            )
        )
        self.getConnection().commit()
        cur.close()
        return v_id


    def get( self, image_id ):
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM %s " % self._table_name+
            "WHERE image_id=%(id)s",
            {"id": image_id}
        )
        vectors = cur.fetchall()
        cur.close()

        for i in range(len(vectors)):

            v_str = vectors[i]["vector"]

            code = vectors[i]["mode"]

            if code == 'g':
                v_str = zlib.decompress(v_str)

            vectors[i]["vector"] = tuple([
                ord(v) for v in v_str
            ])

        return vectors


    def remove_by_file(self, file_id):
        cur = self.getCursor()
        rc = cur.execute("DELETE FROM %s " % self._table_name +
                         "WHERE file_id=%(id)s", {"id": file_id})
        self.getConnection().commit()
        cur.close()
        return rc


    pass
